/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.simu.towercrane.activity;

import android.R.integer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.LogUtil.log;
import com.avos.avoscloud.SignUpCallback;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.simu.constant.TableConstant;
import com.simu.towercrane.DemoApplication;
import com.simu.towercrane.R;
import com.simu.towercrane.myactivty.MsgVerificationActivity;
import com.easemob.exceptions.EaseMobException;

/**
 * 注册页
 * 
 */
public class RegisterActivity extends BaseActivity {
	private EditText userNameEditText;
	private EditText passwordEditText;
	private EditText confirmPwdEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		userNameEditText = (EditText) findViewById(R.id.username);
		userNameEditText.setInputType(InputType.TYPE_CLASS_PHONE);//你能输入电话
		passwordEditText = (EditText) findViewById(R.id.password);
		confirmPwdEditText = (EditText) findViewById(R.id.confirm_password);
	}

	/**
	 * 注册
	 * 
	 * @param view
	 */
	public void register(View view) {	
		String st1 = getResources().getString(R.string.User_name_cannot_be_empty);
		String st2 = getResources().getString(R.string.Password_cannot_be_empty);
		String st3 = getResources().getString(R.string.Confirm_password_cannot_be_empty);
		String st4 = getResources().getString(R.string.Two_input_password);
		String st5 = getResources().getString(R.string.Is_the_registered);
		final String st6 = getResources().getString(R.string.Registered_successfully);
		final String username = userNameEditText.getText().toString().trim();
		final String pwd = passwordEditText.getText().toString().trim();
		String confirm_pwd = confirmPwdEditText.getText().toString().trim();
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(this, st1, Toast.LENGTH_SHORT).show();
			userNameEditText.requestFocus();
			return;
		} else if (TextUtils.isEmpty(pwd)) {
			Toast.makeText(this, st2, Toast.LENGTH_SHORT).show();
			passwordEditText.requestFocus();
			return;
		} else if (TextUtils.isEmpty(confirm_pwd)) {
			Toast.makeText(this, st3, Toast.LENGTH_SHORT).show();
			confirmPwdEditText.requestFocus();
			return;
		} else if (!pwd.equals(confirm_pwd)) {
			Toast.makeText(this, st4, Toast.LENGTH_SHORT).show();
			return;
		}

		if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
			final ProgressDialog pd = new ProgressDialog(this);
			pd.setMessage(st5);
			pd.show();		
			new Thread(new Runnable() {
				public void run() {
					AVUser user = new AVUser();
					user.setUsername(username);
					user.setPassword(pwd);
					// 其他属性可以像其他AVObject对象一样使用put方法添加
					user.setMobilePhoneNumber(username);
					user.signUpInBackground(new SignUpCallback() {//注册leanclound账号
					    public void done(AVException e) {
					        if (e == null) {
					            // successfully
					        	Toast.makeText(getApplicationContext(), "LeanClound注册成功", Toast.LENGTH_SHORT).show();
					         	registerInHX(pd,username,TableConstant.UserDefaultPWDInHX);//注册环信账号
					        } else {
					            // failed
					        	pd.dismiss();
					        	Toast.makeText(getApplicationContext(), "LeanClound注册未成功\n"+e.getMessage(), Toast.LENGTH_LONG).show();
					        }
					    }					    					  
					});														
				}						
			}).start();
		}
	}
//注册环信账号
	public void registerInHX(final ProgressDialog pd,final String username,final String pwd){
		new Thread(new Runnable() {//环信的注册方法请求网络数据了的，所以要放在线程中			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {							
					// 调用sdk注册方法				
					EMChatManager.getInstance().createAccountOnServer(username, pwd);
					runOnUiThread(new Runnable() {//注册成功
						public void run() {
							if (!RegisterActivity.this.isFinishing())
								pd.dismiss();
							// 保存用户名
							DemoApplication.getInstance().setUserName(username);
							Toast.makeText(getApplicationContext(), "注册环信成功", 0).show();
							finish();
							Intent intent=new Intent(getApplicationContext(), MsgVerificationActivity.class);
							intent.putExtra("userName", username);
							startActivity(intent);
						}
					});
				} catch (final EaseMobException  e) {
					messageAfterFailRegisterHX(pd,e);					
					hanleAfterFialRegisterHX(username,pwd);
					pd.dismiss();
				}
			}
		}).start();
	}

	//注册环信失败后显示的信息
	public void messageAfterFailRegisterHX(final ProgressDialog pd,final EaseMobException e){
		runOnUiThread(new Runnable() {//注册未成功
			public void run() {
				if (!RegisterActivity.this.isFinishing())
					pd.dismiss();
				int errorCode=e.getErrorCode();
				final String st7 = getResources().getString(R.string.network_anomalies);
				final String st8 = getResources().getString(R.string.User_already_exists);
				final String st9 = getResources().getString(R.string.registration_failed_without_permission);
				final String st10 = getResources().getString(R.string.Registration_failed);
				String msg="环信注册失败\n";
				if(errorCode==EMError.NONETWORK_ERROR){
					Toast.makeText(getApplicationContext(), msg+st7, Toast.LENGTH_SHORT).show();
				}else if(errorCode==EMError.USER_ALREADY_EXISTS){
					Toast.makeText(getApplicationContext(), msg+st8, Toast.LENGTH_SHORT).show();
				}else if(errorCode==EMError.UNAUTHORIZED){
					Toast.makeText(getApplicationContext(),msg+st9, Toast.LENGTH_SHORT).show();
				}else{
					String ed=st10+e.getMessage();
					Toast.makeText(getApplicationContext(), msg+st10 + e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	//注册环信失败后的操作
	public void hanleAfterFialRegisterHX(String username, String pwd){
	    AVUser.logInInBackground(username, pwd, new LogInCallback<AVUser>() {			
			@Override
			public void done(AVUser arg0, AVException arg1) {
				// TODO Auto-generated method stub		
				arg0.deleteInBackground(new DeleteCallback() {
					@Override
					public void done(AVException arg0) {
						// TODO Auto-generated method stub	
						Log.e("register", "删除leanClean账户失败");
					}
				});	
			}
		});	
	}
	
	public void back(View view) {
		finish();
	}

}
